<?php
class Admin_PhoneController extends Zend_Controller_Action {
	public function init() {
		/* Initialize action controller here */
	}
	public function indexAction() {
		$phoneDb = new Application_Model_DbTable_Phone();
		$select = $phoneDb->select();
		$select->from(array('p' => 'phone'))
			   ->joinInner(array('c'=> 'catagory'),'p.catagory_id = c.id' ,array())
			   ->where('c.del_flag = 0')
			   ->where('p.del_flag=0');
		$phones = $phoneDb->fetchAll ( $select );
		$this->view->phones = $phones;
	}
	
	public function detailAction(){
		$phoneId  = $this->_request->getParam("id");
		$phoneDb = new Application_Model_DbTable_Phone();
		$phone = $phoneDb->find($phoneId)->current();
		$currentCatagory = $phone->findParentRow("Application_Model_DbTable_Catagory");
		$tags = $phone->findDependentRowset("Application_Model_DbTable_Tag");
		
		$this->view->phone = $phone;
		$this->view->currentCatagory = $currentCatagory;
		$this->view->tags = $tags;
	}
	
	public function editAction() {
		$this->view->errors = array ();
		$phoneId = (int) $this->getRequest()->getParam("id");
		$phoneDb = new Application_Model_DbTable_Phone();
		$phone = $phoneDb->find($phoneId)->current();
		$tags = $phone->findDependentRowset("Application_Model_DbTable_Tag");
		$catagoryDb = new Application_Model_DbTable_Catagory();
		$catagories = $catagoryDb->fetchAll('del_flag = 0');
		if ($this->getRequest ()->isPost ()) {
			
			$result = $this->savePhone( $this->_request->getPost (), $phoneId );
				
			if (! is_array ( $result )) {
				$this->view->success = true;
			} else {
				$this->view->errors = $result;
			}
			$phone->screen 		= $this->getRequest ()->getParam ( "screen" );
			$phone->os 			= $this->getRequest ()->getParam ( "os" );
			$phone->cpu 		= $this->getRequest ()->getParam ( "cpu" );
			$phone->camera 		= $this->getRequest ()->getParam ( "camera" );
			$phone->pin 		= $this->getRequest ()->getParam ( "pin" );
			$phone->cpu		 	= $this->getRequest ()->getParam ( "cpu" );
			$phone->memory 		= $this->getRequest ()->getParam ( "memory" );
			$phone->name 		= $this->getRequest ()->getParam ( "name" );
			$phone->catagory_id = $this->getRequest ()->getParam ( "catagory-id" );
			$phone->price 		= $this->getRequest ()->getParam ( "price" );
			$phone->color 		= $this->getRequest ()->getParam ( "color" );
		}
			
		$this->view->phone = $phone;
		$this->view->tags = $tags;
		$this->view->catagories = $catagories;
		$this->view->action = WEB_PATH . '/admin/phone/edit/id/' . $phoneId;
	}
	public function addAction() {
		$this->view->errors = array ();
		$catagoryDb = new Application_Model_DbTable_Catagory();
		$catagories = $catagoryDb->fetchAll('del_flag = 0');
		
		$phoneDb = new Application_Model_DbTable_Phone();
		
		if ($this->getRequest ()->isPost ()) {
			
			$result = $this->savePhone( $this->_request->getPost ());
				
			if (! is_array ( $result )) {
				$this->redirect('/admin/phone');
			} else {
				$this->view->errors = $result;
			}
			$this->view->screen 		= $this->getRequest ()->getParam ( "screen" );
			$this->view->os 			= $this->getRequest ()->getParam ( "os" );
			$this->view->cpu 			= $this->getRequest ()->getParam ( "cpu" );
			$this->view->camera 		= $this->getRequest ()->getParam ( "camera" );
			$this->view->pin 			= $this->getRequest ()->getParam ( "pin" );
			$this->view->sim		 	= $this->getRequest ()->getParam ( "sim" );
			$this->view->memory 		= $this->getRequest ()->getParam ( "memory" );
			$this->view->name 			= $this->getRequest ()->getParam ( "name" );
			$this->view->catagoryId 	= $this->getRequest ()->getParam ( "catagory-id" );
			$this->view->price 			= $this->getRequest ()->getParam ( "price" );
			$this->view->color 			= $this->getRequest ()->getParam ( "color" );
		}
		$this->view->action = WEB_PATH . '/admin/phone/add';
		$this->view->catagories = $catagories;
	}
	
	public function deleteAction() {
		$phoneId = (int) $this->getRequest()->getParam("id");
		$phoneDb = new Application_Model_DbTable_Phone();
		$where = $phoneDb->getAdapter()->quoteInto("id=?", $phoneId);
		
		$phoneDb->update(array('del_flag' => 1), $where);
		$this->redirect('/admin/phone');
	}
	
	public function uploadimgAction(){
		$phoneId = (int) $this->getRequest()->getParam("id");
		if ($this->getRequest ()->isPost ()) {
			$errors = array ();
			$phoneDb = new Application_Model_DbTable_Phone();
			$where = $phoneDb->getAdapter()->quoteInto("id=?", $phoneId);
			
			$adapter = new Zend_File_Transfer_Adapter_Http();
			$adapter->setDestination(APPLICATION_PATH . '/../public/imgs');
			
			$adapter->addValidator('Extension', true, 'jpg,png,gif');
			$adapter->addValidator('IsImage', false);
			$adapter->addValidator('Size', true, array(
					'min' => '1kB' ,
					'max' => '1MB' ,
					'bytestring' => false));

			$files = $adapter->getFileInfo();
			
			foreach ($files as $file => $info) {
				// file uploaded ?
				if (!$adapter->isUploaded($file)) {
					$errors[] = "Làm ơn chọn file upload";
				} else {
			
					// validators are ok ?
					if (!$adapter->isValid($file)) {
						$errors[] = "File không hợp lệ, kiểm tra lại kích thước ảnh và dung lượng file.";
					}
				}
			}
			if (count ( $errors ) == 0) {
				if (!$adapter->receive()){
					$errors = $adapter->getMessages();
				}
				$filepath = $adapter->getFileName('image-file');
				$fileExt = $this->getFileExtension($filepath);
				$filename = basename($filepath, $fileExt);
				$phoneDb->update(array('image_url' => $filename . $fileExt), $where);
				$this->redirect('/admin/phone/edit/id/' . $phoneId);
			}
			$this->view->errors = $errors;
		}
		
		$this->view->id = $phoneId;
	}
	
	public function savePhone($data, $phoneId = null) {
		$phoneDb = new Application_Model_DbTable_Phone();
		// Initialize the errors array
		$errors = array ();

		// name
		if (! Zend_Validate::is ( $data ['name'], 'NotEmpty' )) {
			$errors [] = "'Tên sản phẩm' không được để trống.";
		}
		
		// Screen
		if (! Zend_Validate::is ( $data ['screen'], 'NotEmpty' )) {
			$errors [] = "'Màn hình' không được để trống.";
		}
		
		// OS
		if (! Zend_Validate::is ( $data ['os'], 'NotEmpty' )) {
			$errors [] = "'Hệ điều hành' không được để trống.";
		}
		
		// CPU
		if (! Zend_Validate::is ( $data ['cpu'], 'NotEmpty' )) {
			$errors [] = "'CPU' không được để trống.";
		}
		
		// Camera
		if (! Zend_Validate::is ( $data ['camera'], 'NotEmpty' )) {
			$errors [] = "'Camera' không được để trống.";
		}
		
		// Memory
		if (! Zend_Validate::is ( $data ['memory'], 'NotEmpty' )) {
			$errors [] = "'Bộ nhớ trong' không được để trống.";
		}
		
		// PIN
		if (! Zend_Validate::is ( $data ['pin'], 'NotEmpty' )) {
			$errors [] = "'pin' không được để trống.";
		}
		
		
		// If no errors, insert the
		if (count ( $errors ) == 0) {
				
			$data = array (
					'screen' => $data ['screen'],
					'name' => $data ['name'],
					'os' => $data ['os'],
					'cpu' => $data ['cpu'],
					'pin' => $data ['pin'],
					'memory' => $data ['memory'],
					'sim' => $data ['sim'],
					'camera' => $data ['camera'],
					'catagory_id' => (int) $data ['catagory-id'],
					'price' => (int) $data ['price'],
					'color' => $data ['color'],
			);
			$where = $phoneDb->getAdapter()->quoteInto("id=?", $phoneId);
			if ($phoneId == null) {
				return $phoneDb->insert($data);
			} else {
				return $phoneDb->update($data, $where);
			}
		} else {
			return $errors;
		}
	}
	
	public function getFileName($path, $ext) {
		return $bname = basename($path, $ext);
	}
	
	public function getFileExtension($path) {
		return $ext = strrchr($path, '.');
	}
	
}

